<template>
    <div class="searchAddress">
        <Header title="选择城市和地址" left-arrow :noBack="true"  @click-left="back"/>
        <Search v-model="searchValue" placeholder="请输入地址"  class="search" @update:model-value="onSearch(searchValue)">
            <template #left-icon>
                <span class="search-city" @click.stop="showAction=true">{{ currentCity.name }}<i class="iconfont icon-zhankai"></i></span><span class="line">|</span>  <i class="iconfont icon-sousuo"></i>
            </template>
        </Search>
        <div class="select-box">
            <div class="select-num">
                已选择<span>{{ selectProjectName.length }}项</span>
            </div>
            <div v-if="selectProjectName.length" class="select-list">
                <span v-for="(item,index) in selectProjectName" :key="index" @click="onSelect(item)">
                    {{ item.title||item.address }} <Icon name="cross" />
                </span>
            </div>
            <div class="search-list">
                <ul>
                    <li v-for="(item,index) in projectNameList" :key="index" class="search-item" @click="onSelect(item)">
                        <div>
                            <p v-html="item.addressHtml?item.addressHtml:item.title"></p>
                        </div>
                        <Icon v-if="selectProjectTitle.includes(item.title)" name="checked" color="#E60044" size="18px" />
                    </li>
                </ul>
            </div>
        </div>
        <!-- <div class="btn-box">
            <Button class="pre-btn" type="primary" plain hairline @click="onReset">
                <span>重置</span>
            </Button>
            <Button class="next-btn" type="primary" @click="onSaveProject">
                <span>确定</span>
            </Button>
        </div> -->
        <div>
            <div class="fe-btns">
                <div class="left" @click="onReset">
                    重置
                </div>
                <div class="right"  @click="onSaveProject">
                    确定
                </div>
            </div>
            <div class="van-safe-area-bottom"></div>
        </div>
        <CitySelect :show-action="showAction" @confirm="onSelectConfirm" @close="showAction=false"></CitySelect>
    </div>
</template>

<script lang="ts" setup>
import {ref,defineEmits,computed,defineExpose,defineProps,PropType,toRefs,watch,onMounted} from 'vue';
import {Search ,Icon,Toast,Button, List } from 'vant';
import type { SearchInstance } from 'vant';
import {CityAddressModel,LocalSearchModel} from './../TopSelect/topSelecter.module.d';
import {TreeChildModel} from './../CitySelecter/citySelecter.module';
import CitySelect from '@/components/CitySelecter/index.vue';
import Header from '@/components/Header/index.vue';
import { useRouter } from 'vue-router';
import { store } from '@/store';
import { Console } from 'console';
const router = useRouter();
const props = defineProps({
    currentCity: {
        type: Object as PropType<TreeChildModel>,
        require: true,
        default: () => ({}),
    },
    show: {
        type: Boolean,
        default: false,
    },
});

const { currentCity }= toRefs(props);
const emits = defineEmits(['onConfirm','onCel','changCity']);

const searchValue = ref('');
const projectNameList= ref<CityAddressModel[]>([]);
const selectProjectName = ref<CityAddressModel[]>([]);
const showAction = ref(false);

const onSearch = (query: string) => {
    if (query) {
        Toast.loading({
            message: '加载中....',
            forbidClick: true,
            duration: 0, // 持续展示 toast
        });
        try {
            // eslint-disable-next-line;
            const local = new BMap.LocalSearch(currentCity.value.name, {
                onSearchComplete: (res: LocalSearchModel) => {
                    const list = res ? res.Yr: [];
                    let localList = onLocalList(list);
                    projectNameList.value = localList.map((item:CityAddressModel)=>{
                        return {...item,addressHtml: item.title.replace(query,`<span style="color:#F7135E">${query}</span>`)};
                    });
                    Toast.clear();
                },
            });
            Toast.clear();
            // eslint-disable-next-line;
            local.search(query, {
                forceLocal: true,
            });
        } catch (error) {
            console.log(error);
            Toast.clear();
        }
    }

};
const onLocalList = (list:CityAddressModel[])=>{
    let obj = {} as CityAddressModel;
    let LocalList = list.reduce((cur,next) => {
        obj[next.title] ? "" : obj[next.title] = true && cur.push(next);
        return cur;
    },[])
    return LocalList
}
const onSelect = (item:CityAddressModel)=>{
    const index = selectProjectName.value.findIndex((selectItem:CityAddressModel)=>selectItem.title===item.title);
    if(index>-1){
        selectProjectName.value.splice(index,1);
    }else{
        selectProjectName.value.push(item);
    }
};
const onSaveProject = ()=>{
    searchValue.value ='';
    if(selectProjectName.value.length){
        emits('onConfirm',selectProjectName.value);
    }else{
        Toast.fail('请选择搜索地址');
    }
};
const onReset = ()=>{
    searchValue.value ='';
    selectProjectName.value = [];
    projectNameList.value = [];
};
const onSelectConfirm = (val:TreeChildModel)=>{
    showAction.value = false;
    onReset()
    emits('changCity',val);

};
const back = () => {
     emits('onCel')  
};
const uuid = ()=> {
	let s = [] as unknown as any;
	let hexDigits = "0123456789abcdef";
	for (var i = 0; i < 36; i++) {
		s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
	}
	s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
	s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
	s[8] = s[13] = s[18] = s[23] = "-";

	var uuid = s.join("");
	return uuid;
}
const selectProjectTitle= computed(() => selectProjectName.value.map(item=>item.title));
const listAddress = computed(() => store.state.app.selectByLbs.addresses);
const city = computed(() => store.state.app.selectByLbs.city);

watch(()=>currentCity.value,()=>{
    searchValue.value ='';  
},{
    deep: true,
});
const showListAddress = ()=>{
    if(currentCity.value.name !==city.value.name){
           selectProjectName.value = [] ;
           projectNameList.value = []
        }else{
            if(listAddress.value&&listAddress.value.length){
                let listAddressLbs = listAddress.value.map(item=>{
                    return {...item,uid:uuid()}
                })
            let list = JSON.parse(JSON.stringify(listAddressLbs))
                selectProjectName.value = listAddressLbs as unknown as CityAddressModel[];
                projectNameList.value = list;
            }else{
                selectProjectName.value = [];
                projectNameList.value = []; 
            }
               
        }
}
watch(()=>props.show,(val)=>{
    if(val){
        searchValue.value ='';
        showListAddress()          
    }
   
});

onMounted(()=>{
 showListAddress()
})
// 对外暴露可执行方法
defineExpose({
    onReset,
});
</script>

<style lang="scss" scoped>
.searchAddress {
    display: flex;
    flex-direction: column;
    min-height: 100vh;
    height: 100vh;
}
.select-box {
    padding: 12px;
    flex: 1;
    overflow: auto;

    .select-num {
        span {
            color: #e60044;
        }
    }
    .select-list {
        display: flex;
        flex-direction: row;
        margin-top: 16px;
        white-space: nowrap;
        max-width: 100%;
        overflow-y: hidden;
        -webkit-overflow-scrolling: touch;
        span {
            display: inline-block;
            height: 28px;
            background: #fafafa;
            border-radius: 4px;
            font-size: 12px;
            color: #333333;
            letter-spacing: 0;
            line-height: 28px;
            margin-right: 12px;
            padding: 0 12px;
        }
        ::-webkit-scrollbar {
            width: 0;
            height: 0;
            display: none;
        }
    }
    .search-list {
        .search-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            // height: 56.5px;
            border-bottom: 0.5px solid #eeeeee;
            padding: 16px 0;
            p {
                color: #333333;
                font-size: 14px;
            }
            span {
                font-size: 12px;
                color: #848484;
            }
        }
    }
}
.fe-btns {
    margin-top: 12px;
    box-shadow: 0 -2px 4px 0 #ebebeb80;
    display: flex;
    padding: 6px 12px 0;
    margin-bottom: 8px;
    div {
        display: flex;
        justify-content: center;
        align-items: center;
    }
    .left {
        width: 120px;
        height: 38px;
        line-height: 38px;
        background: #ffffff;
        border: 0.5px solid #e60044;
        border-radius: 6px;
        font-weight: 400;
        font-size: 14px;
        color: #e60044;
        text-align: center;
        margin-right: 12px;
    }
    .right {
        width: calc(100% - 120px);
        height: 38px;
        line-height: 38px;
        background: #e60044;
        border: 0.5px solid #e60044;
        border-radius: 6px;
        // font-family: PingFangSC-SNaNpxibold;
        font-weight: 600;
        font-size: 14px;
        color: #ffffff;
        text-align: center;
    }

    .disabled {
        background: #f06690;
    }
}
.search-city {
    color: #333;
    .icon-zhankai {
        display: inline-block;
        font-size: 12px;
        transform: scale(0.6, 0.6);
        color: #ddd;
        padding-left: 5px;
    }
}
.line {
    color: #eee;
    vertical-align: top;
    padding: 0 10px;
}
</style>
